import asyncio
import time
from asyncio import AbstractEventLoop

from common.utility import Utility

def sync_func(sleep_time: int = 2):
    Utility.print_info(f'entered. It will sleep {sleep_time} seconds.')
    time.sleep(sleep_time)
    Utility.print_info('exited.')

async def say_after(content: str, delay: int = 1) -> None:
    Utility.print_info(f'entered. It will delay {delay} seconds.')
    await asyncio.sleep(delay)
    Utility.print_info(content)
    Utility.print_info('exited.')

# 在异步中运行同步
async def asyncio_to_thread():
    Utility.print_info('entered.')
    await asyncio.gather(
        asyncio.to_thread(sync_func, 2),
        say_after('hello'))
    Utility.print_info('exited.')

# 在同步中调用异步
def sync_func2(loop: AbstractEventLoop, sleep_time: int = 1):
    Utility.print_info('entered.')
    time.sleep(sleep_time)
    # 创建一个协程
    coro = say_after('hello',1)
    # 将协程提交给给定的循环
    future = asyncio.run_coroutine_threadsafe(coro, loop)
    future.result(2)
    Utility.print_info('exited.')

async def asyncio_threadsafe():
    Utility.print_info('entered.')
    # 获取正在运行的循环
    loop: AbstractEventLoop = asyncio.get_running_loop()
    # 在线程中运行一些东西
    await asyncio.to_thread(sync_func2, loop)
    Utility.print_info('exited.')

#asyncio.run(asyncio_to_thread())
asyncio.run(asyncio_threadsafe())